package cn.edu.scnu.semart.goods.service.Impl;

import cn.edu.scnu.semart.model.goods.Goods;
import cn.edu.scnu.semart.goods.mapper.GoodsMapper;
import cn.edu.scnu.semart.goods.service.GoodsService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 商品Service实现类
 */
@Service
public class GoodsServiceImpl extends ServiceImpl<GoodsMapper, Goods> implements GoodsService {

    @Autowired
    private GoodsMapper goodsMapper;
    @Override
    public IPage<Goods> searchGoods(Page<Goods> page, String keyword, Integer categoryId,
                                    Double minPrice, Double maxPrice, String sortBy, String sortOrder) {
        // 确保只查询审核通过且上架的商品
        return baseMapper.searchGoods(page, keyword, categoryId, minPrice, maxPrice,
                sortBy, sortOrder, 1, 1); // auditStatus=1, status=1
    }

    @Override
    public IPage<Goods> searchAllAuditStatusGoods(Page<Goods> page, String keyword, Integer categoryId,
                                                  Double minPrice, Double maxPrice, String sortBy,
                                                  String sortOrder, Integer auditStatus) {
        // 不限制审核状态和商品状态，允许管理员查看所有商品
        return baseMapper.searchAllAuditStatusGoods(page, keyword, categoryId, minPrice, maxPrice,
                sortBy, sortOrder, auditStatus);
    }


    @Override
    public Goods getGoodsDetail(Integer id) {
        return getById(id);
    }

    @Override
    public IPage<Goods> getGoodsByCategory(Integer categoryId, Page<Goods> page) {
        QueryWrapper<Goods> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("category_id", categoryId)
                   .eq("status", 1)
                   .orderByDesc("create_time");
        return page(page, queryWrapper);
    }

    @Override
    public IPage<Goods> getGoodsByUserId(Integer userId, Page<Goods> page) {
        QueryWrapper<Goods> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId)
                .orderByDesc("create_time");
        return page(page, queryWrapper);
    }

    @Override
    public List<Goods> getHotGoods(Integer limit) {
        QueryWrapper<Goods> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", 1)
                   .orderByDesc("sales")
                   .last("LIMIT " + limit);
        return list(queryWrapper);
    }

    @Override
    public List<Goods> getRecommendGoods(Integer limit) {
        QueryWrapper<Goods> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", 1)
                   .orderByDesc("likes")
                   .last("LIMIT " + limit);
        return list(queryWrapper);
    }

    @Override
    public boolean updateSales(Integer goodsId, Integer quantity) {
        UpdateWrapper<Goods> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", goodsId)
                    .setSql("sales = sales + " + quantity);
        return update(updateWrapper);
    }

    @Override
    public boolean updateStock(Integer goodsId, Integer quantity) {
        UpdateWrapper<Goods> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", goodsId)
                    .setSql("stock = stock + " + quantity);
        return update(updateWrapper);
    }

    @Override
    public IPage<Goods> getPendingAuditGoods(Page<Goods> page) {
        QueryWrapper<Goods> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("audit_status", 0)  // 待审核
                   .orderByDesc("create_time");
        return page(page, queryWrapper);
    }

    @Override
    public IPage<Goods> getAuditedGoods(Page<Goods> page) {
        QueryWrapper<Goods> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("audit_status", 1)  // 审核通过
                   .orderByDesc("audit_time");
        return page(page, queryWrapper);
    }

    @Override
    public IPage<Goods> getRejectedGoods(Page<Goods> page) {
        QueryWrapper<Goods> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("audit_status", 2)  // 审核拒绝
                   .orderByDesc("audit_time");
        return page(page, queryWrapper);
    }

    @Override
    public IPage<Goods> getGoodsByAuditStatus(Integer auditStatus, Page<Goods> page) {
        QueryWrapper<Goods> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("audit_status", auditStatus)
                   .orderByDesc("create_time");
        return page(page, queryWrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean directApprove(Integer goodsId, Integer auditorId, String auditorName, String remark) {
        // 先获取商品当前状态
        Goods goods = getById(goodsId);
        if (goods == null) {
            throw new RuntimeException("商品不存在");
        }

        // 检查商品是否已经是审核通过状态
        if (goods.getAuditStatus() == 1) {
            throw new RuntimeException("商品已审核通过，不能重复操作");
        }

        // 检查商品是否是审核拒绝状态
        if (goods.getAuditStatus() == 2) {
            throw new RuntimeException("商品已审核拒绝");
        }

        UpdateWrapper<Goods> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", goodsId)
                .set("status", 1)  // 上架状态
                .set("audit_status", 1)  // 审核通过
                .set("auditor_id", auditorId)
                .set("auditor_name", auditorName)
                .set("audit_time", LocalDateTime.now())
                .set("audit_remark", remark);
        return update(updateWrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean directReject(Integer goodsId, Integer auditorId, String auditorName, String rejectReason) {
        // 先获取商品当前状态
        Goods goods = getById(goodsId);
        if (goods == null) {
            throw new RuntimeException("商品不存在");
        }

        // 检查商品是否已经是审核拒绝状态
        if (goods.getAuditStatus() == 2) {
            throw new RuntimeException("商品已审核拒绝，不能重复操作");
        }

        // 检查商品是否是审核通过状态
        if (goods.getAuditStatus() == 1) {
            throw new RuntimeException("商品已审核通过");
        }

        UpdateWrapper<Goods> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", goodsId)
                .set("status", 4)  // 审核拒绝状态
                .set("audit_status", 2)  // 审核拒绝
                .set("auditor_id", auditorId)
                .set("auditor_name", auditorName)
                .set("audit_time", LocalDateTime.now())
                .set("reject_reason", rejectReason);
        return update(updateWrapper);
    }

    // ========== 榜单统计相关方法实现 ==========

    @Override
    public List<Goods> getSalesRanking(Integer limit, Integer categoryId) {
        QueryWrapper<Goods> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", 1)  // 上架状态
                   .eq("audit_status", 1);  // 审核通过
        if (categoryId != null) {
            queryWrapper.eq("category_id", categoryId);
        }
        queryWrapper.orderByDesc("sales")
                   .last("LIMIT " + limit);
        return list(queryWrapper);
    }

    @Override
    public List<Goods> getLikesRanking(Integer limit, Integer categoryId) {
        QueryWrapper<Goods> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", 1)  // 上架状态
                   .eq("audit_status", 1);  // 审核通过
        if (categoryId != null) {
            queryWrapper.eq("category_id", categoryId);
        }
        queryWrapper.orderByDesc("likes")
                   .last("LIMIT " + limit);
        return list(queryWrapper);
    }

    @Override
    public List<Goods> getFavoritesRanking(Integer limit, Integer categoryId) {
        QueryWrapper<Goods> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", 1)  // 上架状态
                   .eq("audit_status", 1);  // 审核通过
        if (categoryId != null) {
            queryWrapper.eq("category_id", categoryId);
        }
        queryWrapper.orderByDesc("favorites")
                   .last("LIMIT " + limit);
        return list(queryWrapper);
    }

    @Override
    public List<Goods> getHotRanking(Integer limit, Integer categoryId) {
        QueryWrapper<Goods> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", 1)  // 上架状态
                   .eq("audit_status", 1);  // 审核通过
        if (categoryId != null) {
            queryWrapper.eq("category_id", categoryId);
        }
        // 综合热度：销量 + 点赞数 + 收藏数
        queryWrapper.orderByDesc("(sales + likes + favorites)")
                   .last("LIMIT " + limit);
        return list(queryWrapper);
    }

    @Override
    public List<Goods> getNewRanking(Integer limit, Integer categoryId) {
        QueryWrapper<Goods> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", 1)  // 上架状态
                   .eq("audit_status", 1);  // 审核通过
        if (categoryId != null) {
            queryWrapper.eq("category_id", categoryId);
        }
        queryWrapper.orderByDesc("create_time")
                   .last("LIMIT " + limit);
        return list(queryWrapper);
    }

    @Override
    public List<Goods> getLowPriceRanking(Integer limit, Integer categoryId) {
        QueryWrapper<Goods> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", 1)  // 上架状态
                   .eq("audit_status", 1);  // 审核通过
        if (categoryId != null) {
            queryWrapper.eq("category_id", categoryId);
        }
        queryWrapper.orderByAsc("price")
                   .last("LIMIT " + limit);
        return list(queryWrapper);
    }

    @Override
    public List<Goods> getHighPriceRanking(Integer limit, Integer categoryId) {
        QueryWrapper<Goods> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", 1)  // 上架状态
                   .eq("audit_status", 1);  // 审核通过
        if (categoryId != null) {
            queryWrapper.eq("category_id", categoryId);
        }
        queryWrapper.orderByDesc("price")
                   .last("LIMIT " + limit);
        return list(queryWrapper);
    }

    @Override
    public List<Goods> getComprehensiveRanking(Integer limit, Integer categoryId) {
        QueryWrapper<Goods> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", 1)  // 上架状态
                   .eq("audit_status", 1);  // 审核通过
        if (categoryId != null) {
            queryWrapper.eq("category_id", categoryId);
        }
        // 综合评分：销量*0.4 + 点赞数*0.3 + 收藏数*0.3
        queryWrapper.orderByDesc("(sales * 0.4 + likes * 0.3 + favorites * 0.3)")
                   .last("LIMIT " + limit);
        return list(queryWrapper);
    }

    @Override
    public List<Goods> getCategoryRanking(Integer categoryId, Integer limit, String sortBy) {
        QueryWrapper<Goods> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", 1)  // 上架状态
                   .eq("audit_status", 1)  // 审核通过
                   .eq("category_id", categoryId);
        
        switch (sortBy) {
            case "sales":
                queryWrapper.orderByDesc("sales");
                break;
            case "likes":
                queryWrapper.orderByDesc("likes");
                break;
            case "favorites":
                queryWrapper.orderByDesc("favorites");
                break;
            case "price":
                queryWrapper.orderByDesc("price");
                break;
            case "create_time":
                queryWrapper.orderByDesc("create_time");
                break;
            default:
                queryWrapper.orderByDesc("sales");
        }
        
        queryWrapper.last("LIMIT " + limit);
        return list(queryWrapper);
    }

    @Override
    public Map<String, Object> getRankingStatistics() {
        Map<String, Object> statistics = new HashMap<>();
        
        // 统计总商品数
        QueryWrapper<Goods> totalQuery = new QueryWrapper<>();
        totalQuery.eq("status", 1).eq("audit_status", 1);
        Integer totalGoods = Math.toIntExact(count(totalQuery));
        statistics.put("totalGoods", totalGoods);
        
        // 统计各分类商品数
        QueryWrapper<Goods> categoryQuery = new QueryWrapper<>();
        categoryQuery.eq("status", 1).eq("audit_status", 1)
                    .select("category_id, COUNT(*) as count")
                    .groupBy("category_id");
        // 这里可以进一步处理分类统计
        
        // 统计销量最高的商品
        List<Goods> topSales = getSalesRanking(1, null);
        if (!topSales.isEmpty()) {
            statistics.put("topSalesGoods", topSales.get(0));
        }
        
        // 统计点赞最高的商品
        List<Goods> topLikes = getLikesRanking(1, null);
        if (!topLikes.isEmpty()) {
            statistics.put("topLikesGoods", topLikes.get(0));
        }
        
        // 统计收藏最高的商品
        List<Goods> topFavorites = getFavoritesRanking(1, null);
        if (!topFavorites.isEmpty()) {
            statistics.put("topFavoritesGoods", topFavorites.get(0));
        }
        
        // 统计最新商品
        List<Goods> latestGoods = getNewRanking(1, null);
        if (!latestGoods.isEmpty()) {
            statistics.put("latestGoods", latestGoods.get(0));
        }
        
        return statistics;
    }

    public List<Goods> getBatchByIds(List<Integer> ids) {
        if (ids == null || ids.isEmpty()) {
            return Collections.emptyList();
        }
        return goodsMapper.selectBatchByIds(ids);
    }
    /**
     * 扣减库存（事务管理）
     */
    @Transactional(rollbackFor = Exception.class)
    public Boolean deductStock(Map<Integer, Integer> deductMap) {
        for (Map.Entry<Integer, Integer> entry : deductMap.entrySet()) {
            Integer goodsId = entry.getKey();
            Integer deductNum = entry.getValue();

            // 1. 查询当前库存
            Goods goods = goodsMapper.selectById(goodsId);
            if (goods == null) {
                throw new RuntimeException("商品不存在: " + goodsId);
            }

            // 2. 检查库存是否充足
            if (goods.getStock() < deductNum) {
                throw new RuntimeException("库存不足: 商品ID=" + goodsId);
            }

            // 3. 扣减库存（乐观锁更新）
            int updated = goodsMapper.reduceStock(goodsId, deductNum, goods.getStock());
            if (updated == 0) {
                throw new RuntimeException("扣减库存失败: 商品ID=" + goodsId);
            }
        }
        return true;
    }

    /**
     * 恢复库存（事务管理）
     */
    @Transactional(rollbackFor = Exception.class)
    public Boolean restoreStock(Map<Integer, Integer> restoreMap) {
        for (Map.Entry<Integer, Integer> entry : restoreMap.entrySet()) {
            Integer goodsId = entry.getKey();
            Integer restoreNum = entry.getValue();

            // 直接增加库存（无需检查当前库存）
            goodsMapper.increaseStock(goodsId, restoreNum);
        }
        return true;
    }

    public IPage<Goods> getUserPendingAuditGoods(Page<Goods> page, Integer userId) {
        QueryWrapper<Goods> queryWrapper = new QueryWrapper();
        ((QueryWrapper)((QueryWrapper)queryWrapper.eq("audit_status", 0)).eq("user_id", userId)).orderByDesc("create_time");
        return this.page(page, queryWrapper);
    }

    public IPage<Goods> getUserAuditedGoods(Page<Goods> page, Integer userId) {
        QueryWrapper<Goods> queryWrapper = new QueryWrapper();
        ((QueryWrapper)((QueryWrapper)queryWrapper.eq("audit_status", 1)).eq("user_id", userId)).orderByDesc("audit_time");
        return this.page(page, queryWrapper);
    }

    public IPage<Goods> getUserRejectedGoods(Page<Goods> page, Integer userId) {
        QueryWrapper<Goods> queryWrapper = new QueryWrapper();
        ((QueryWrapper)((QueryWrapper)queryWrapper.eq("audit_status", 2)).eq("user_id", userId)).orderByDesc("audit_time");
        return this.page(page, queryWrapper);
    }

    @Override
    public void incrementLikeCount(Integer goodsId) {
        baseMapper.incrementLikeCount(goodsId);
    }

    @Override
    public void decrementLikeCount(Integer goodsId) {
        baseMapper.decrementLikeCount(goodsId);
    }

    @Override
    public void incrementFavoriteCount(Integer goodsId) {
        baseMapper.incrementFavoriteCount(goodsId);
    }

    @Override
    public void decrementFavoriteCount(Integer goodsId) {
        baseMapper.decrementFavoriteCount(goodsId);
    }
} 